package com.dmwork.service.work.controller.front;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dmwork.common.base.result.ExceptionUtils;
import com.dmwork.common.base.result.R;
import com.dmwork.common.base.util.JwtInfo;
import com.dmwork.common.base.util.JwtUtils;
import com.dmwork.service.work.entity.Work;
import com.dmwork.service.work.entity.WorkType;
import com.dmwork.service.work.entity.vo.WorkBaseInfoVo;
import com.dmwork.service.work.entity.vo.WorkDetailInfoVo;
import com.dmwork.service.work.entity.vo.WorkQueryVo;
import com.dmwork.service.work.feign.CustomerFeignService;
import com.dmwork.service.work.feign.WorkCollectFeignService;
import com.dmwork.service.work.service.WorkService;
import com.dmwork.service.work.service.WorkTypeService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Slf4j
@Api(description = "全局作品功能管理")
@Transactional
@RestController
@RequestMapping("/front/dm_work/work")
public class FrontWorkController {

    @Autowired
    private WorkService workService;
    @Autowired
    private WorkCollectFeignService workCollectFeignService;
    @Autowired
    private WorkTypeService workTypeService;
    @Autowired
    private CustomerFeignService customerFeignService;

    @ApiOperation("获取作品列表")
    @GetMapping("get_list/{page}/{limit}")
    public R getList(@PathVariable("page") Integer page, @PathVariable("limit") Integer limit, WorkQueryVo workQueryVo) {
        Page<WorkBaseInfoVo> workBaseInfoVoPage = workService.getWorkPage(workQueryVo, page, limit);
        if (workBaseInfoVoPage.getTotal() == 0) {
            return R.ok().message("暂无数据").data("total", 0);
        }
        //获取每个作品的对应用户名
        List<String> customerIdList = new ArrayList<>();
        //获取作品id列表
        List<String> workIdList=new ArrayList<>(workBaseInfoVoPage.getRecords().size());
        for (WorkBaseInfoVo workBaseInfoVo : workBaseInfoVoPage.getRecords()) {
            customerIdList.add(workBaseInfoVo.getCustomerId());
            workIdList.add(workBaseInfoVo.getId());
        }
        R briefInfoResult = customerFeignService.getBriefInfoList(customerIdList);
        HashMap<String, List<String>> infoMap = (HashMap<String, List<String>>) briefInfoResult.getData().get("result");

        Map<String, Integer> collectCountMap = workCollectFeignService.getBatchCollectCountByWorkIdList(workIdList);

        for (WorkBaseInfoVo workBaseInfoVo : workBaseInfoVoPage.getRecords()) {
            workBaseInfoVo.setCustomerName(infoMap.get(workBaseInfoVo.getCustomerId()).get(0));
            workBaseInfoVo.setCollectCount(collectCountMap.get(workBaseInfoVo.getId()));
            //转换作品标题中的Emoji
            workBaseInfoVo.setTitle(EmojiParser.parseToUnicode(workBaseInfoVo.getTitle()));
        }
        return R.ok().data("total", workBaseInfoVoPage.getTotal()).data("rows", workBaseInfoVoPage.getRecords());
    }

    @ApiOperation("获取指定类型热门作品")
    @GetMapping("hot/{count}/{typeId}")
    public R hot(@PathVariable("count") Integer count, @PathVariable("typeId") String typeId) {
        List<WorkBaseInfoVo> workBaseInfoVoList = workService.getHotList(count, typeId);
        if (workBaseInfoVoList.size() == 0) {
            return R.ok().message("暂无数据").data("total", 0);
        }
        //获取每个作品的对应用户名
        List<String> customerIdList = new ArrayList<>();
        //获取作品id列表
        List<String> workIdList=new ArrayList<>(workBaseInfoVoList.size());
        for (WorkBaseInfoVo workBaseInfoVo : workBaseInfoVoList) {
            customerIdList.add(workBaseInfoVo.getCustomerId());
            workIdList.add(workBaseInfoVo.getId());
        }
        R briefInfoResult = customerFeignService.getBriefInfoList(customerIdList);
        HashMap<String, List<String>> infoMap = (HashMap<String, List<String>>) briefInfoResult.getData().get("result");

        Map<String, Integer> collectCountMap = workCollectFeignService.getBatchCollectCountByWorkIdList(workIdList);

        for (WorkBaseInfoVo workBaseInfoVo : workBaseInfoVoList) {
            workBaseInfoVo.setCustomerName(infoMap.get(workBaseInfoVo.getCustomerId()).get(0));
            workBaseInfoVo.setCollectCount(collectCountMap.get(workBaseInfoVo.getId()));
            //转换作品标题中的Emoji
            workBaseInfoVo.setTitle(EmojiParser.parseToUnicode(workBaseInfoVo.getTitle()));
        }
        return R.ok().data("items", workBaseInfoVoList);
    }

    @ApiOperation("增加指定作品热度")
    @PutMapping("hot_up/{workId}")
    public R hotUp(@ApiParam(value = "作品id", required = true) @PathVariable("workId") String workId) {
        Work work = workService.getById(workId);
        work.setHot(work.getHot() + 1);
        workService.updateById(work);
        return R.ok().message("热度增加成功");
    }

    @ApiOperation("获取指定用户作品列表")
    @GetMapping("get_info_list/{customerId}/{page}/{limit}")
    public R getInfoList(
            @ApiParam(value = "指定用户id", required = true) @PathVariable("customerId") String customerId,
            @ApiParam(value = "页数", required = true) @PathVariable("page") Integer page,
            @ApiParam(value = "分页", required = true) @PathVariable("limit") Integer limit) {

        Page<WorkBaseInfoVo> workBaseInfoVoPage = workService.getWorkBaseInfoPageByCustomerId(customerId, page, limit);
        if (workBaseInfoVoPage.getTotal() == 0) {
            return R.ok().message("暂无数据").data("total", 0);
        }
        R baseInfoResult = customerFeignService.getBaseInfo(customerId);
        String customerName = (String) baseInfoResult.getData().get("customerName");

        //获取作品id列表
        List<String> workIdList=new ArrayList<>(workBaseInfoVoPage.getRecords().size());
        for (WorkBaseInfoVo workBaseInfoVo : workBaseInfoVoPage.getRecords()) {
            workIdList.add(workBaseInfoVo.getId());
        }
        Map<String, Integer> collectCountMap = workCollectFeignService.getBatchCollectCountByWorkIdList(workIdList);

        for (WorkBaseInfoVo workBaseInfoVo : workBaseInfoVoPage.getRecords()) {
            workBaseInfoVo.setCustomerName(customerName);
            workBaseInfoVo.setCollectCount(collectCountMap.get(workBaseInfoVo.getId()));
            //转换作品标题中的Emoji
            workBaseInfoVo.setTitle(EmojiParser.parseToUnicode(workBaseInfoVo.getTitle()));
        }
        return R.ok().data("total", workBaseInfoVoPage.getTotal()).data("rows", workBaseInfoVoPage.getRecords());
    }

    @ApiOperation("获取指定作品详情")
    @GetMapping("get_info/{workId}")
    public R getInfo(
            HttpServletRequest request,
            @ApiParam(value = "作品id", required = true) @PathVariable("workId") String workId) {

        WorkDetailInfoVo workDetailInfoVo = workService.getWorkDetailInfoById(workId);
        List<WorkType> workTypeList = workTypeService.list();
        for (WorkType workType : workTypeList) {
            if (workType.getId().equals(workDetailInfoVo.getTypeId())) {
                workDetailInfoVo.setTypeName(workType.getName());
                break;
            }
        }
        JwtInfo jwtToken = null;
        try {
            jwtToken = JwtUtils.getCustomerInfoByJwtToken(request);
        } catch (Exception e) {
            ExceptionUtils.getMessage(e);
        }

        Boolean collected = false;
        //根据是否有token来判断是否处于登录状态，如果为非登录状态，则不返回网盘链接及验证码
        if (jwtToken == null) {
            workDetailInfoVo.setNetdiskUrl(null);
            workDetailInfoVo.setNetdiskCode(null);
        } else { //如果token不为空，则发送请求验证当前作品是否被当前用户收藏
            R r = workCollectFeignService.checkWorkIsCollected(workId);
            collected = (Boolean) r.getData().get("collected");
        }
        //转换作品标题和简介中的Emoji
        workDetailInfoVo.setTitle(EmojiParser.parseToUnicode(workDetailInfoVo.getTitle()));
        workDetailInfoVo.setDescription(EmojiParser.parseToUnicode(workDetailInfoVo.getDescription()));

        return R.ok().data("item", workDetailInfoVo).data("collected", collected);
    }

    @ApiOperation("获取指定用户的指定收藏分组的作品列表")
    @GetMapping("get_collect_list/{customerId}/{collectGroupId}/{page}/{limit}")
    public R getCollectList(
            @ApiParam(value = "用户id", required = true) @PathVariable("customerId") String customerId,
            @ApiParam(value = "收藏分组id", required = true) @PathVariable("collectGroupId") String collectGroupId,
            @ApiParam(value = "页数", required = true) @PathVariable("page") Integer page,
            @ApiParam(value = "每页记录数", required = true) @PathVariable("limit") Integer limit) {

        //OpenFeign获取作品id列表
        R result = workCollectFeignService.getWorkIdList(customerId, collectGroupId, page, limit);
        if (result.getSuccess()) {
            Gson gson = new Gson();
            String json = gson.toJson(result.getData().get("workIdList"));
            String total = gson.toJson(result.getData().get("total"));
            List<String> workIdList = gson.fromJson(json, new TypeToken<List<String>>() {
            }.getType());
            log.info(Arrays.toString(workIdList.toArray()));
            if (workIdList.size() == 0) {
                return R.ok().data("total", total).data("rows", null);
            }
            log.info(Arrays.toString(workIdList.toArray()));
            List<WorkBaseInfoVo> workBaseInfoVoList = workService.getWorkBaseInfoListByIds(workIdList);
            //获取每个作品的对应用户名
            List<String> customerIdList = new ArrayList<>();
            for (WorkBaseInfoVo workBaseInfoVo : workBaseInfoVoList) {
                customerIdList.add(workBaseInfoVo.getCustomerId());
            }
            R briefInfoResult = customerFeignService.getBriefInfoList(customerIdList);

            Map<String, Integer> collectCountMap = workCollectFeignService.getBatchCollectCountByWorkIdList(workIdList);

            HashMap<String, List<String>> infoMap = (HashMap<String, List<String>>) briefInfoResult.getData().get("result");
            for (WorkBaseInfoVo workBaseInfoVo : workBaseInfoVoList) {
                workBaseInfoVo.setCustomerName(infoMap.get(workBaseInfoVo.getCustomerId()).get(0));
                workBaseInfoVo.setCollectCount(collectCountMap.get(workBaseInfoVo.getId()));
                //转换作品标题中的Emoji
                workBaseInfoVo.setTitle(EmojiParser.parseToUnicode(workBaseInfoVo.getTitle()));
            }
            return R.ok().data("total", total).data("rows", workBaseInfoVoList);
        } else {
            return result;
        }
    }
}
